package org.strangewt.jface.viewers;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.strangewt.widgets.IInput;

public class CompositeViewer extends Composite implements IInput {
	
	private Composite 			detailComposite;
	private ICompositeProvider 	compositeProvider;
	private boolean				enabled = true;
	
	public CompositeViewer(Composite parent, int style) {
		super(parent, style);
		
		GridLayout layout = new GridLayout();
		layout.horizontalSpacing = 0;
		layout.verticalSpacing = 0;
		layout.marginHeight = 0;
		layout.marginWidth = 0;
		setLayout(layout);
	}
	
	/** 
	 * @param if null the <code>ICompositeProvider</code> gets the class 
	 * ICompositeProvider.class handed over. Composite gefragt. 
	 */
	public void setInput(Object o) {
		if(o != null) {
			Class<?> clazz = compositeProvider.getCompositeClass(o);
			if(clazz != null) {
				createDetailComposite(clazz);
				
				if(detailComposite instanceof IInput) {
					((IInput)detailComposite).setInput(o);
				}
			}
		} else {
			if(compositeProvider != null) {
				createDetailComposite(compositeProvider.getCompositeClass(this));
			}
		}
	}
	
	public Object getInput() {
		if(detailComposite != null) {
			if(detailComposite instanceof IInput) {
				return ((IInput)detailComposite).getInput();
			}
		}
		return null;
	}
	
	public void createDetailComposite(Class<?> clazz) {
		if (detailComposite != null) {
			detailComposite.dispose();
			detailComposite = null;
		}

		if (detailComposite == null) {
			try {
				detailComposite = (Composite) clazz
									.getConstructor(Composite.class, int.class)
									.newInstance(this, SWT.NONE);
				
				detailComposite.setEnabled(enabled);
				detailComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
				this.layout(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public ICompositeProvider getCompositeProvider() {
		return compositeProvider;
	}
	
	public void setCompositeProvider(ICompositeProvider compositeProvider) {
		this.compositeProvider = compositeProvider;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
		if(detailComposite != null) {
			detailComposite.setEnabled(enabled);
		}
	}
	
	public Composite getComposite() {
		return detailComposite;
	}
	
	public boolean isInputClass(Class clazz) {
		Object input = getInput();
		if(input != null && input.getClass() == clazz) {
			return true;
		}
		
		return false;
	}
}

